<template>
  <div class="form">
    <div class="formTip">
      <van-image :src="img"></van-image>
      <p>我们将以短信的形式发送验证码至您的手机</p>
    </div>
    <van-field
      v-model="telcode"
      center
      clearable
      placeholder="请输入短信验证码"
    >
      <template #button>
        <van-button :disabled="time < 10" size="small" @click="sendCodeFn">{{ text }}</van-button>
      </template>
    </van-field>
    <div class="my-button">
      <van-button :disabled="flag" color="#ff6666" @click="checkCodeFn" block round>下一步</van-button>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { Field, Button, Image as VanImage, Toast } from 'vant'
import { doSendMsgCode, doCheckCode } from '@/api/user'
Vue.use(Field)
Vue.use(Button)
Vue.use(VanImage)
Vue.use(Toast)
export default {
  data () {
    return {
      img: '',
      telcode: '',
      text: '发送短信验证码',
      time: 10, // 10秒倒计时
      timer: null // 计时器
    }
  },
  computed: {
    flag () {
      if (this.telcode.length < 4) {
        return true
      } else {
        return false
      }
    }
  },
  mounted () {
    this.sendCodeFn()
  },
  methods: {
    checkCodeFn () {
      doCheckCode({
        tel: localStorage.getItem('tel'),
        telcode: this.telcode
      }).then(res => {
        if (res.data.code === '10007') {
          Toast('验证码输入错误')
        } else {
          this.$router.push('/register/step3')
        }
      })
    },
    sendCodeFn () {
      // 调用接口发送验证码
      doSendMsgCode({ tel: localStorage.getItem('tel') }).then(res => {
        console.log(res.data)
        Toast('短信验证码已发送至您的手机，请注意查收')
      })
      // 效果
      this.timer = setInterval(() => {
        this.text = this.time + 's后重新发送'
        this.time--
        if (this.time === -1) {
          clearTimeout(this.timer)
          this.time = 10
          this.text = '发送短信验证码'
        }
      }, 1000)
    }
  }
}
</script>
<style lang="stylus">
.form
  .formTip
    display flex
    height 200px
    flex-direction column
    justify-content center
    align-items center

  .my-button
    margin-top 30px
</style>
